package com.lxl.securitypermission.config.custom;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lxl.securitypermission.pojo.SecUser;
import com.lxl.securitypermission.service.MenuService;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

/**
 * @author 绫小路
 * @date 2020/12/29 23:58
 * @description
 */
@Slf4j
@Component //交给spring托管
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  @Autowired
  private MenuService menuService;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
      Authentication authentication) throws IOException, ServletException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", 0);
    jsonObject.put("message", "登录成功！");
    //登录后，返回原访问页面
    RequestCache cache = new HttpSessionRequestCache();
    SavedRequest savedRequest = cache.getRequest(httpServletRequest, httpServletResponse);
    String url = "0";
    try {
      url = savedRequest.getRedirectUrl();
      if (url.contains("register")) {
        url = "/";
      }
    } catch (Exception e) {
      url = "/";
    }
    jsonObject.put("url", url);
    //重新存储user对象到session
    SecUser securityUser = (SecUser) authentication.getPrincipal();
    System.out.println(securityUser);

    //让浏览器用utf8来解析返回的数据
    httpServletResponse.setHeader("Content-type", "application/json;charset=utf-8");
    httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
    httpServletResponse.getWriter().write(jsonObject.toJSONString());
    //记录日志
    log.info("登录者信息  会话：{} , 角色：{} , 信息：{}",
        authentication.getDetails(),
        authentication.getAuthorities(),
        authentication.getPrincipal()
    );
    //获取菜单信息
    httpServletRequest.getSession().setAttribute("menu", menuService.getMenuList(securityUser.getId()));
  }
}
